package com.kiku.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kiku.reggie.common.CustomException;
import com.kiku.reggie.dto.SetmealDto;
import com.kiku.reggie.entity.Setmeal;

import com.kiku.reggie.entity.SetmealDish;
import com.kiku.reggie.mapper.SetMealMapper;
import com.kiku.reggie.service.SetMealDishService;
import com.kiku.reggie.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @className: SetMealServiceImpl
 * @description: TODO 类描述
 * @author: kiku
 * @date: 2023/10/19 21:49
 **/
@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper,Setmeal> implements SetMealService {
    @Autowired
    private SetMealDishService setMealDishService;

    //新增套餐并且同时保存套餐和菜品的关联关系
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息,操作setMeal表(insert)
        this.save(setmealDto);
        //保存套餐和菜品的关联信息，操作的是setMealDish表(insert)
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setMealDishService.saveBatch(setmealDishes);
    }

    //删除套餐并且删除套餐和菜品的关联关系
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐的状态，确定是否可以进行删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        //如果不能进行删除，就抛出一个业务异常
        if (count>0){
            //不可进行删除
            throw new CustomException("套餐正在售卖中，不可进行删除");
        }
        //如果可以进行删除，先删除套餐表中的数据
        this.removeByIds(ids);
        //删除关系表的数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setMealDishService.remove(lambdaQueryWrapper);

    }
}
